import gzip
import logging
import mimetypes
import os
from pathlib import Path

from accounts.models import FeatureSwitch
from django.conf import settings
from django.http import Http404, HttpResponse
from django.shortcuts import render
from django.utils.http import http_date
import django

logger = logging.getLogger(__name__)


def home(request):
    """首页视图"""
    context = {
        'code_operations_enabled': FeatureSwitch.is_feature_enabled('code_operations'),
        'battle_creation_enabled': FeatureSwitch.is_feature_enabled('battle_creation'),
    }
    return render(request, 'home.html', context)


def serve_static_gzip(request, path):
    """
    自定义静态文件服务，支持 gzip 压缩
    支持项目静态文件和Django admin静态文件
    """
    
    # 首先尝试项目静态文件目录
    file_path = os.path.join(settings.BASE_DIR, 'static', path)
    
    # 如果项目静态文件不存在，尝试Django内置静态文件
    if not os.path.exists(file_path) or not os.path.isfile(file_path):
        # 检查是否是admin静态文件
        if path.startswith('admin/'):
            # 获取Django安装路径下的admin静态文件
            django_path = Path(django.__file__).parent
            admin_static_path = django_path / 'contrib' / 'admin' / 'static' / path
            if admin_static_path.exists() and admin_static_path.is_file():
                file_path = str(admin_static_path)
            else:
                logger.error(f'Admin static file not found: {admin_static_path}')
                raise Http404('Admin static file not found')
        else:
            # 尝试在STATICFILES_DIRS中查找
            for static_dir in getattr(settings, 'STATICFILES_DIRS', []):
                potential_path = os.path.join(static_dir, path)
                if os.path.exists(potential_path) and os.path.isfile(potential_path):
                    file_path = potential_path
                    break
            else:
                logger.error(f'Static file not found: {path}')
                raise Http404('Static file not found')

    # 获取文件的 MIME 类型
    content_type, encoding = mimetypes.guess_type(file_path)
    if content_type is None:
        content_type = 'application/octet-stream'

    # 检查客户端是否支持 gzip
    accept_encoding = request.META.get('HTTP_ACCEPT_ENCODING', '')
    use_gzip = 'gzip' in accept_encoding.lower()

    try:
        # 读取文件内容
        with open(file_path, 'rb') as f:
            content = f.read()

        # 如果支持 gzip 且文件大于 1KB，则进行压缩
        if use_gzip and len(content) > 1024:
            # 压缩内容
            compressed_content = gzip.compress(content)

            # 创建响应
            response = HttpResponse(compressed_content, content_type=content_type)
            response['Content-Encoding'] = 'gzip'
            response['Content-Length'] = len(compressed_content)
            logger.debug(
                f'Serving gzipped content, original: {file_path} {len(content)}, compressed: {len(compressed_content)}'
            )
        else:
            # 不压缩，直接返回原始内容
            response = HttpResponse(content, content_type=content_type)
            response['Content-Length'] = len(content)

        # 设置缓存相关头部
        file_stat = os.stat(file_path)
        response['Last-Modified'] = http_date(file_stat.st_mtime)
        response['ETag'] = f'"{file_stat.st_mtime}-{file_stat.st_size}"'

        # 设置缓存控制
        response['Cache-Control'] = 'public, max-age=86400'  # 缓存1天

        return response

    except IOError as e:
        logger.error(f'Error reading static file {file_path}: {e}')
        raise Http404('Error reading static file')
